package com.time.hellotime.webserver.helper.picasso;

import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

import com.squareup.picasso.Transformation;
import com.yanzhenjie.nohttp.Logger;

/**
 * 高斯模糊处理
 * Author: Created by deng on 2016/7/4.
 * E-mail: tx16bing@163.com
 */
public class BlurTransformation implements Transformation {

    private Context mContext;
    // Set the radius of the Blur. Supported range 0 < radius <= 25
    private static final float DEFAULT_BLUR_RADIUS = 20f;

    public BlurTransformation(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public Bitmap transform(Bitmap bitmapToBlur) {
        Bitmap outputBitmap = bitmapToBlur;
        // Android 4.2
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {

            try {

                Bitmap U8_4Bitmap;
                if (bitmapToBlur.getConfig() == Bitmap.Config.ARGB_8888) {
                    U8_4Bitmap = bitmapToBlur;
                }
                else {
                    U8_4Bitmap = bitmapToBlur.copy(Bitmap.Config.ARGB_8888, true);
                }

                outputBitmap = Bitmap.createBitmap(U8_4Bitmap.getWidth(), U8_4Bitmap.getHeight(), U8_4Bitmap.getConfig());

                final RenderScript renderScript = RenderScript.create(mContext);
                final Allocation input = Allocation.createFromBitmap(
                        renderScript,
                        U8_4Bitmap,
                        Allocation.MipmapControl.MIPMAP_NONE,
                        Allocation.USAGE_SCRIPT
                );
                final Allocation output = Allocation.createTyped(
                        renderScript,
                        input.getType()
                );

                // Intrinsic Gausian blur filter
                final ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, output.getElement());
                theIntrinsic.setRadius(DEFAULT_BLUR_RADIUS);
                theIntrinsic.setInput(input);
                theIntrinsic.forEach(output);
                output.copyTo(outputBitmap);

                renderScript.destroy();
            }
            catch (Exception e) {
                Logger.e("Cannot blur image, return the original image instead");
                e.printStackTrace();
                outputBitmap = bitmapToBlur;
            }
        }
        if (outputBitmap != null) {
            //内存回收
            bitmapToBlur.recycle();
        }
        return outputBitmap;
    }

    @Override
    public String key() {
        return "blur";
    }
}
